/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.postp.postp_view.command;

import java.awt.Toolkit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.commons.command.Command;
import br.ufmg.dees.insane.commons.view.ExtensionFileFilter;
import br.ufmg.dees.insane.model.postp.PostpModel;
import br.ufmg.dees.insane.ui.rich.postp.postp_view.DesktopPostp;
import br.ufmg.dees.insane.ui.rich.postp.postp_view.InterfacePostp;
import br.ufmg.dees.insane.xyplot.xyplot_model.XYPlot;
import br.ufmg.dees.insane.xyplot.xyplot_view.InterfaceXYPlot;

/**
 * This class is a implementation of the interface Command.
 * its unabled to undo or redo.
 * its "execute" method verify the existence of a model, and
 * if that is one, it calls a file chooser to set the models name and
 * the save routine is called.
 *
 * @author Penna, Samuel & Fonseca, Flavio & Pitangueira, Roque
 * @since 05/07/2006
 * @see postp_view.command.Command
 */
public class SaveFileCommand implements Command {
    
    private DesktopPostp parent;
    private JFileChooser fileChooser = new JFileChooser();
    private ExtensionFileFilter filter = new ExtensionFileFilter("ipp", "INSANE-POSTP Files");
	private boolean validFile;
	
//*****************************************************************************
	
    /**
     * Creates new SaveFileCommand
     * and sets the FileFilter do FileChooser.
     *
     * @param parent The JFrame parent.
     */
    public SaveFileCommand(JFrame parent) {
        this.parent = (DesktopPostp)parent;
        fileChooser.setFileFilter(filter);
    }
	
//*****************************************************************************
	
    /**
     * Saves the current model accordding to ModelState name.
     * If ModelState has its initial name it prompts a dialog to
     * choose another name.
     *
     * @see gui.command.Command#execute()
     */ 
    public void execute() {
    	if(parent.getDesktop().getSelectedFrame() instanceof InterfacePostp){
    		if (((InterfacePostp)parent.getDesktop().getSelectedFrame()).getPostpModel() != null) {
    			if (((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().getName().equals("untitled.ipp")){
    				
    				validFile = false;
    				while (!validFile) {
    					int retVal = fileChooser.showSaveDialog(parent);
    					if (retVal == JFileChooser.APPROVE_OPTION) {
    						
    						//Getting the file name
    						String s = fileChooser.getSelectedFile().getName();
    						
    						//Getting the file extension
    						String ext = new String();
    						int i = s.lastIndexOf('.');
    						if (i > 0 &&  i < s.length() - 1) {
    							ext = s.substring(i+1).toLowerCase();
    						}
    						
    						//Comparing the extension
    						if (!ext.equals("ipp")) {
    							s = s + ".ipp";
    							File file = fileChooser.getSelectedFile();
    							
    							//Changing the file in case of no good extensions
    							fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
    						}
    						
    						//Checks if the file exists
    						if (fileChooser.getSelectedFile().exists()){
    							int value = 10;
    							value = JOptionPane.showConfirmDialog(parent,
    							"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
    							"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    							if (value == JOptionPane.YES_OPTION){
    								validFile = true;
    							}
    						}
    						else {
    							validFile = true;
    						}
    					}
    					else return;
    				}
    				
    				
    				((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().setName(fileChooser.getSelectedFile().getName());
    				((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().setPath(fileChooser.getSelectedFile().getPath());
    				save();
    				
    			}else {
    				fileChooser.setSelectedFile(new File(((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().getPath()));
    				save();
    			}
    			
    			((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getDrawingArea().repaint();
    		}
    	
    	}else if(parent.getDesktop().getSelectedFrame() instanceof InterfaceXYPlot){
    		if (((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getModel() != null) {
    			if (((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().getName().equals("untitled.ipp")){
    				
    				validFile = false;
    				while (!validFile) {
    					int retVal = fileChooser.showSaveDialog(parent);
    					if (retVal == JFileChooser.APPROVE_OPTION) {
    						
    						//Getting the file name
    						String s = fileChooser.getSelectedFile().getName();
    						
    						//Getting the file extension
    						String ext = new String();
    						int i = s.lastIndexOf('.');
    						if (i > 0 &&  i < s.length() - 1) {
    							ext = s.substring(i+1).toLowerCase();
    						}
    						
    						//Comparing the extension
    						if (!ext.equals("ipp")) {
    							s = s + ".ipp";
    							File file = fileChooser.getSelectedFile();
    							
    							//Changing the file in case of no good extensions
    							fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
    						}
    						
    						//Checks if the file exists
    						if (fileChooser.getSelectedFile().exists()){
    							int value = 10;
    							value = JOptionPane.showConfirmDialog(parent,
    							"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
    							"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    							if (value == JOptionPane.YES_OPTION){
    								validFile = true;
    							}
    						}
    						else {
    							validFile = true;
    						}
    					}
    					else return;
    				}
    				
    				
    				((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().setName(fileChooser.getSelectedFile().getName());
    				((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().setPath(fileChooser.getSelectedFile().getPath());
    				save();
    				
    			}else {
    				fileChooser.setSelectedFile(new File(((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().getPath()));
    				save();
    			}
    			
    			((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getDrawingArea().repaint();
    		}
    	
    	}
	}//end of method
    
//*****************************************************************************
	
    /**
     * Writes model on disc using a FileOutputStream and 
     * an ObjectOutputStream.
     */
    private void save() {
    	if(parent.getDesktop().getSelectedFrame() instanceof InterfacePostp){
    		try{
    			((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().setCurrentZoom(
    					((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getDrawingArea().getCurrentZoom());
                FileOutputStream serialStream = new FileOutputStream(fileChooser.getSelectedFile());
                ObjectOutputStream stream = new ObjectOutputStream(serialStream);
                stream.writeObject((PostpModel)((InterfacePostp)parent.getDesktop().getSelectedFrame()).getPostpModel());
                serialStream.flush();
    			parent.setTitle("INSANE " + parent.getProperties().getVersion() + " - " +((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().getName());
    		}catch (Exception exc){
                Toolkit.getDefaultToolkit().beep();
                JOptionPane.showMessageDialog(parent, "Couldn't save file!", "Error Message", JOptionPane.ERROR_MESSAGE);
            }
    	}else if(parent.getDesktop().getSelectedFrame()instanceof InterfaceXYPlot){
    		try{
    			((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getViewState().setCurrentZoom(
    					((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getView().getDrawingArea().getCurrentZoom());
                FileOutputStream serialStream = new FileOutputStream(fileChooser.getSelectedFile());
                ObjectOutputStream stream = new ObjectOutputStream(serialStream);
                stream.writeObject((XYPlot)((InterfaceXYPlot)parent.getDesktop().getSelectedFrame()).getModel());
                serialStream.flush();
    			parent.setTitle("INSANE " + parent.getProperties().getVersion() + " - " +((InterfacePostp)parent.getDesktop().getSelectedFrame()).getView().getViewState().getName());
    		}catch (Exception exc){
                Toolkit.getDefaultToolkit().beep();
                JOptionPane.showMessageDialog(parent, "Couldn't save file!", "Error Message", JOptionPane.ERROR_MESSAGE);
            }
    	}
    	
    }
    
//*****************************************************************************
	
    /**
     * Impossible to undo - not implemented.
     */
    public void undo() {}
    
//*****************************************************************************
	
    /**
     * Impossible to redo - not implemented.
     */
    public void redo() {}
    
//*****************************************************************************
}

